/*
Author:HuZhixin
Date:2020-06-19
content:user operator
 */
const userDao=require('../dao/userDao');
const md5=require('../utils/md5/md5');


//1.注册：判断，查找用户存在，否则增加
async function addUser(user) {
    user.password = md5.toMd5(user.password);
  var ret=await userDao.findByName(user.name);
  // console.log(ret)
  //   console.log(ret.success)
  if(ret.success){
      return {success:false,msg:'用户已存在'};
  }else{
      // console.log(user);
      var data=await userDao.addUser(user);
      //在dao中已做数据处理，直接...
      // console.log(data);
      return data;
  }
}


// 2.登录：查出用户，进行密码比对
//对数据库里的密码进行MD5验证,所以密码一般要进行密码验证
async function login(user) {
    var ret=await userDao.findByName(user.name);
    if(ret.success){
        var password=md5.toMd5(user.password);
        if(password==ret.user.password){
            return  {success:true,user:ret.user};
        }else {
            return {success:false,msg:'密码不正确'}
        }
    }
    else {
        return {success:false,msg:'用户名不存在'};
    }
};


async function logincookie(user) {
    var ret=await userDao.findByName(user.name);
    if(ret.success){
        if(user.password==ret.user.password){
            return  {success:true,user:ret.user};
        }else {
            return {success:false,msg:'密码不正确'}
        }
    }
    else {
        return {success:false,msg:'用户名不存在'};
    }
};

exports.addUser=addUser;
exports.login=login;
exports.logincookie=logincookie;